package cn.stylefeng.guns.sys.modular.tao.service.serviceImpl;

import cn.stylefeng.guns.sys.modular.api.controller.ApiController;
import cn.stylefeng.guns.sys.modular.api.sdk.RandomStringUtils;
import cn.stylefeng.guns.sys.modular.api.sdk.Utils;
import cn.stylefeng.guns.sys.modular.tao.entity.Member;
import cn.stylefeng.guns.sys.modular.tao.entity.MemberSpecs;
import cn.stylefeng.guns.sys.modular.tao.entity.WxUser;
import cn.stylefeng.guns.sys.modular.tao.mapper.MemberMapper;
import cn.stylefeng.guns.sys.modular.tao.model.params.RechargeRecordParam;
import cn.stylefeng.guns.sys.modular.tao.service.MemberService;
import cn.stylefeng.guns.sys.modular.tao.service.MemberSpecsService;
import cn.stylefeng.guns.sys.modular.tao.service.RechargeRecordService;
import cn.stylefeng.guns.sys.modular.tao.service.WxUserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    RechargeRecordService rechargeRecordService;
    @Autowired
    WxUserService wxUserService;
    @Autowired
    MemberSpecsService memberSpecsService;

    /**
     * 查询员信息
     */
    @Override
    public ResponseData getMember(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        try {
            Member member = memberMapper.getMember(map.get("id"));
            data.setCode(200);
            data.setMessage("查询成功");
            data.setData(member);
        } catch (Exception e) {
            data.setCode(500);
            data.setMessage("查询失败");
        }
        return data;
    }


    /**
     * 修改会员信息
     */
    @Override
    public ResponseData editMember(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        try {
            Member memberInfo = new Member();
            memberInfo.setId(Long.valueOf(String.valueOf(map.get("id"))));
            memberInfo.setUpdateTime(Utils.getTime());
            memberInfo.setCommission(new BigDecimal(map.get("commission").toString()));
            memberInfo.setPurchaseQuota(new BigDecimal(map.get("purchaseQuota").toString()));
            memberInfo.setDelSign(map.get("delSign").toString());
            memberInfo.setIntegral(Long.parseLong(String.valueOf(map.get("integral"))));
            Member member = memberMapper.editMember(memberInfo);
            data.setCode(200);
            data.setMessage("修改成功");
            data.setData(member);
        } catch (Exception e) {
            data.setCode(500);
            data.setMessage("修改失败");
        }
        return data;
    }


    /**
     * 添加会员信息
     */
    @Override
    public ResponseData addMember(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        Member memberInfo = new Member();
        try {
            Long integral = Long.parseLong("0");
            memberInfo.setDelSign("0");
            memberInfo.setPurchaseQuota(new BigDecimal(map.get("ipurchaseQuota").toString()));
            memberInfo.setId(Long.valueOf(String.valueOf(map.get("id"))));
            memberInfo.setCreateTime(Utils.getTime());
            memberInfo.setCommission(new BigDecimal(map.get("commission").toString()));
            memberInfo.setIntegral(integral);
            Member member = memberMapper.addMember(memberInfo);
            data.setCode(200);
            data.setMessage("添加成功");
            data.setData(member);
        } catch (Exception e) {
            data.setCode(500);
            data.setMessage("添加失败");
        }
        return data;
    }

    /**
     * 删除会员信息
     *
     * @param map
     * @return
     */
    @Override
    public ResponseData deleteMemberInfo(Map<String, Object> map) {
        ResponseData data = new ResponseData();
        Member memberInfo = new Member();
        try {
            memberInfo.setDelSign("1");
            memberInfo.setId(Long.valueOf(String.valueOf(map.get("id"))));
            memberInfo.setUpdateTime(Utils.getTime());
            Member member = memberMapper.deleteMemberInfo(memberInfo);
            data.setCode(200);
            data.setMessage("添加成功");
            data.setData(member);
        } catch (Exception e) {
            data.setCode(500);
            data.setMessage("添加失败");
        }
        return data;
    }

    @Override
    public Member getMemberById(String userId) {
        return memberMapper.getMemberById(userId);
    }

    @Override
    public int add(Member member) {
        return memberMapper.add(member);
    }

    @Override
    public int update(Member promoter) {
        return memberMapper.update(promoter);
    }

    @Override
    public ResponseData BecomeMember(String userId, Integer memberSpecsId, String openId) {
        ResponseData data = new ResponseData();
        //生成订单号
        String orderNos = RandomStringUtils.randomStr(RandomStringUtils.ALL_NUMBER, 5) + Long.toString(System.currentTimeMillis());
        //获取用户信息
        WxUser wxUser = wxUserService.getUserById(userId);
        //获取会员规格信息
        MemberSpecs memberSpecs = memberSpecsService.getById(memberSpecsId);
        //如果用户为第一次充值会员或者之前充值的会员过期
        if(wxUser.getMemberGrade().equals("0")){
            //先创建会员发起记录表  用于记录用户选择了什么类型会员  以便于在微信回调函数中获取做最终设置
            RechargeRecordParam rechargeRecord = new RechargeRecordParam();
            rechargeRecord.setId(orderNos);
            rechargeRecord.setMemberSpecsId(memberSpecsId);
            rechargeRecord.setUserId(userId);
            rechargeRecord.setState(0);
            rechargeRecord.setCreateTime(new Date());
            rechargeRecordService.add(rechargeRecord);
            //调用微信小程序支付接口
            Object Wx = ApiController.wxPay(openId, orderNos, memberSpecs.getVipPrice());
            data.setData(Wx);
            data.setCode(200);
            return data;
        }else{
            //如果用户选择续费或升级自己的会员
            RechargeRecordParam rechargeRecord = new RechargeRecordParam();
            rechargeRecord.setId(orderNos);
            rechargeRecord.setMemberSpecsId(memberSpecsId);
            rechargeRecord.setUserId(userId);
            rechargeRecord.setState(0);
            rechargeRecord.setCreateTime(new Date());
            rechargeRecordService.add(rechargeRecord);
            //如果续费当前的会员  那么花费的金额一致
            if(wxUser.getMemberGrade().equals(memberSpecs.getVipLevel())){
                //金额可能不正确
                Object Wx = ApiController.wxPay(openId, orderNos, memberSpecs.getVipPrice());
                data.setData(Wx);
                data.setCode(200);
                return data;
            }else if(Integer.parseInt(wxUser.getMemberGrade())<Integer.parseInt(memberSpecs.getVipLevel())){
                //如果是升级自己的会员  选择的会员等级大于自己现在的会员等级的时候
                //根据会员等级查询会员规格
                MemberSpecs memberSpecss =   memberSpecsService.getMemberSpecsByLevel(wxUser.getMemberGrade());
                //因为是升级会员 只需要补交差价
                Object Wx = ApiController.wxPay(openId, orderNos, memberSpecs.getVipPrice().subtract(memberSpecss.getVipPrice()));
                data.setData(Wx);
                data.setCode(200);
                return data;
            }else{
                data.setMessage("不能低于现在的会员等级！");
                data.setCode(500);
                return data;
            }

        }
    }
}
